'use strict';
// Copyright 2014 Blueant Inc. All Rights Reserved.

/**
 * @fileoverview 合成士兵
 * @author sundbcn@gmail.com (sun debing)
 */

var _ = require('lodash');
var async = require('async');
var Code = require('../../../../consts/code');
var soldierConf = require('../../../../config/soldierConf');
var PlayerManager = require('../../../../libs/playerManager');

/*
按士兵类型，取出所需的碎片ID和数量
消耗士兵碎片
添加对应士兵
*/
module.exports = function (msg, session, next) {
    var role_id = session.uid;
    var soldier_type = msg.soldier_type;

    var player_manager = new PlayerManager(role_id);
    async.waterfall(
        [
            function (cb) {
                player_manager.refreshData(cb);
            },
            function (cb) {
                player_manager.getModel(['soldier', 'bag', 'accrued'], cb);
            },
            // jshint maxstatements:50
            function (cb) {
                var soldier_model = player_manager.soldier;
                var bag_model = player_manager.bag;

                var soldier_item = soldier_model.getSoldier(soldier_type);
                if (!!soldier_item) {
                    return next(null, {
                        code: Code.SOLDIER_HAVE_UNLOCK
                    });
                }

                var soldier_type_conf = soldierConf.getSoldierTypeConf(soldier_type);
                if (!soldier_type_conf) {
                    return next(null, {
                        code: Code.SOLDIER_NOT_EXIST
                    });
                }

                // 扣除士兵碎片
                if (!bag_model.subProperty(soldier_type_conf.patch_id, soldier_type_conf.start_patch)) {
                    return next(null, {
                        code: Code.USER_SOLDIER_PATCH_NOT_ENOUGH
                    });
                }

                soldier_model.addSoldier(soldier_type, soldier_type_conf.start_star);

                player_manager.save(cb);
            }
        ],
        function (err) {
            if (!!err) {
                console.error(err);
                return next(null, {
                    code: Code.FAIL
                });
            }
            return next(null, {
                code: Code.OK
            });
        }
    );
};
